import { _decorator, Component, Node, __private, Animation, RigidBody2D, PhysicsSystem2D, v3, v2, Collider2D, IPhysics2DContact, Collider, Contact2DType, CircleCollider2D, BoxCollider2D, Sprite, tween, Color, color, } from 'cc';
import { Constant } from '../AshFramework/Datas/Constant';
import { ZTool } from '../AshFramework/Utils/ZTool';
import { EventManager, MyEvent } from '../AshFramework/Managers/EventManager';
import { Chariot } from './Chariot';
import { GameUtil } from './GameUtil';
import { BattleManager } from './BattleManager';
import { GameManager } from './GameManager';
import { TASKTYPE } from '../AshFramework/Datas/GameConstant';
const { ccclass, property } = _decorator;

enum AniState {
    Move = "Monster1_Move",
    Attack = "Monster1_Attack",
    Die = "Monster1_Die",
}

const x = -140;
const minY = -180;
const maxY = 20;

@ccclass('Monster')
export class Monster extends Component {
    @property
    HP: number = 10;

    @property
    CD: number = 3;

    @property
    SpeedX: number = -10;

    @property
    Harm: number = 2;

    @property
    AwardGold: number = 5;

    isDie: boolean = false;
    Sprite: Sprite = null;

    _rigidBody: RigidBody2D = null;
    private _ani: Animation = null;
    private _state: string = AniState.Move;
    _isPlaying: boolean = false;
    private _cb: Function = null;
    private _cd: number = null;

    private _target: Node = null;

    protected onLoad(): void {
        this.Sprite = this.getComponent(Sprite);
        // 注册碰撞回调
        // const boxCollider = this.getComponent(BoxCollider2D);
        const circleCollider = this.getComponent(CircleCollider2D);
        // if (boxCollider) {
        //     boxCollider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);

        // }
        if (circleCollider) {
            circleCollider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            circleCollider.on(Contact2DType.END_CONTACT, this.onEndContact, this);
        }
        this._rigidBody = this.node.getComponent(RigidBody2D);
        this._ani = this.node.getComponent(Animation);

        // 监听动画结束事件
        this._ani.on(Animation.EventType.FINISHED, this.onAnimationFinished, this);
    }
    protected start(): void {
        //初始化出生点
        let y = ZTool.GetRandom(minY, maxY);
        this.node.position = v3(x, y);
        this.AwardGold = Math.floor((1 + GameManager.Instance.userData.propertyAmplification.GOLD / 100) * this.AwardGold);
    }

    protected update(dt: number): void {
        this._rigidBody.linearVelocity = v2(this.SpeedX, 0);
        this._cd += dt;
        if (this._target && this._cd >= this.CD) {
            this._cd = 0;
            this.attack();
        }
    }

    attack() {
        this.PlayAni(AniState.Attack, () => {
            this._isPlaying = false;
            Chariot.Instance.beHit(this.Harm);
            this.PlayAni(AniState.Move)
        })
    }

    PlayAni(state: string, cb: Function = null) {
        if (this._state == state || this._isPlaying) {
            return
        }
        this._state = state;
        if (state === AniState.Attack) {
            this._isPlaying = true;
        }
        this._cb = cb;
        this._ani.crossFade(state);
    }

    onAnimationFinished() {
        this._cb && this._cb();
        this._cb = null;
    }

    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        if (selfCollider.tag == 1 && otherCollider.node.name === "玩家战车") {
            this.SpeedX = 0;
        }
        if (!this._target && otherCollider.node.name === "玩家战车") {
            this._target = otherCollider.node;
        }
    }
    onEndContact(seilfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        if (this._target && otherCollider.node.name === "玩家战车") {
            this._target = null;
        }
    }

    setDirX(x: number) {
        this.SpeedX = x;
    }

    beHit(harm: number) {
        this.HP -= harm;

        tween(this.Sprite)
            .to(0.05, { color: Color.RED }, { easing: `linear` })
            .delay(0.1)
            .to(0.01, { color: Color.WHITE }, { easing: `linear` })
            .start();


        if (this.HP <= 0) {
            EventManager.Scene.emit(MyEvent.REMOVE_MONSTER, this.node);
            this.die();
        }
    }

    die() {
        this.scheduleOnce(() => {
            this._rigidBody.enabled = false;
            this.node.getComponents(CircleCollider2D).forEach(e => e.enabled = false);
            this.PlayAni(AniState.Die, () => {
                if (GameManager.Instance.userData.task.type === TASKTYPE.MONSTER) {
                    GameManager.Instance.userData.task.curProgress++;
                }
                GameUtil.getAwardByMonster(this.node.getWorldPosition().clone(), BattleManager.Instance.getUIGoldWorldPos(), () => {
                    if (this.node && this.node.isValid) {
                        this.node.destroy();
                    }
                    BattleManager.Instance.addAwardGold(this.AwardGold);
                })
            })
            // this.node.active = false;

        })
    }

    protected onEnable(): void {
        EventManager.on(MyEvent.MONSTER_DIRX, this.setDirX, this);
    }
    protected onDisable(): void {
        EventManager.off(MyEvent.MONSTER_DIRX, this.setDirX, this);
    }

}
